
const {app, ipcMain, nativeImage, clipboard} = require('electron')
const path = require('path')
const fs = require('fs')


const DownLoad = {

    mainWindow: null,

    init(mainWindow){

        let _this = this

        this.mainWindow = mainWindow
        //创建tags目录
        let basePath = app.getPath('userData') + '/files'

        if (!fs.existsSync(basePath)) {
            console.log('目录不存在， 创建：' + basePath)
            fs.mkdir(basePath, null, function () {})
        }
        mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
            var copy = false
            var url = item.getURL()
            if(url.endsWith('#copy')){
                copy = true
            }
            if(copy){
                let fileName = item.getFilename()
                const filePath = path.join(basePath, fileName);
                console.log()
                console.log(filePath)

                fs.unlink(filePath, function(err){
                })

                item.setSavePath(filePath);
                item.once('done', (event, state) => {
                    if (state === 'completed') {
                        console.log('Download successfully')
                    } else {
                        console.log(`Download failed: ${state}`)
                    }
                    if(copy){
                        let image = nativeImage.createFromPath(filePath)
                        clipboard.writeImage(image, 'clipboard')
                        copy = false
                    }
                    mainWindow.webContents.send('down-success', {filePath: filePath, fileName: fileName})
                })
                // if(){
                //     //文件已存在，直接返回
                //     console.log('文件已存在，直接返回')
                //     item.cancel()
                //     if(copy){
                //         let image = nativeImage.createFromPath(filePath)
                //         clipboard.writeImage(image, 'clipboard')
                //         copy = false
                //     }
                //     mainWindow.webContents.send('down-success', {filePath: filePath, fileName: fileName, copy: copy})
                // }else{

                // }
            }
        })

        //判断缓存是否存在， 已存在直接返回， 不存在，则下载
        ipcMain.on('download', (event, {url}) => {
            try{
                if(url) mainWindow.webContents.downloadURL(url);
            }catch (e) {
            }
        })


        ipcMain.on('downloadAndCopy', (event, {url}) => {
            if(url) {
                mainWindow.webContents.downloadURL(url + '#copy');
            }
        })

        ipcMain.on('copy', (event, text) => {

        })
    },

}



module.exports = DownLoad
